package com.heima.behavio.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavio.mapper.BhUnLikesMapper;
import com.heima.behavio.service.UserBehaviorService;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.BehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.BhUnLikes;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xjs
 * @date 2022/9/7 14:26
 * description
 */
@Service
public class UserBehaviorServiceImpl extends ServiceImpl<BhUnLikesMapper, BhUnLikes> implements UserBehaviorService {

    @Autowired
    private BhUnLikesMapper bhUnLikesMapper;

    @Autowired
    private UserBehaviorService userBehaviorService;

    @Autowired
    private CacheService cacheService;

    @Transactional
    @Override
    public void likeLog(UnLikesBehaviorDto unLikesBehaviorDto) {
        //将用户不喜欢的记录保存进数据库
        BhUnLikes bhUnLikes = new BhUnLikes();
        ApUser user = ApThreadLocalUtil.getUser();
        bhUnLikes.setArticleId((long)unLikesBehaviorDto.getArticleId());
        bhUnLikes.setType(unLikesBehaviorDto.getType());
        bhUnLikes.setApUserId((long)user.getId());
        userBehaviorService.save(bhUnLikes);
        String key = String.valueOf((unLikesBehaviorDto.getArticleId() +"_"+ user.getId()));

        //查询redis是否有该记录
        String value = cacheService.get(key);
        BehaviorDto behaviorDto = new BehaviorDto();
        //如果有该记录则进行修改
        if(null != value){
            behaviorDto = JSON.parseObject(value, BehaviorDto.class);
            //type为0的话 则为不喜欢
            if (unLikesBehaviorDto.getType() == 0){
                behaviorDto.setIslike(true);
            }else {
                behaviorDto.setIslike(false);
            }
            // 删除以前的记录
            cacheService.delete(key);
        } else {
            //type为0的话 则为不喜欢
            if (unLikesBehaviorDto.getType() == 0){
                behaviorDto.setIslike(true);
            }else {
                behaviorDto.setIslike(false);
            }
            //将记录保存到redis
            cacheService.set(key, JSON.toJSONString(behaviorDto));
        }
        cacheService.set(key, JSON.toJSONString(behaviorDto));

    }

}
